#include <iostream>
#include <SDL/SDL_image.h>
#include <SDL/SDL_ttf.h>
#include "debug.h"
#include "PlayerTurnPrompter.h"
#include "MultiPlayerScreen.h"
#include "SelectScreen.h"
#include "MainWindow.h"

SDL_Surface* MainWindow::m_screen = NULL;
SDL_Event MainWindow::m_event;
bool MainWindow::m_close = false;
TTF_Font* MainWindow::m_font = NULL;
IScreen* MainWindow::m_currentScreen = NULL;
bool MainWindow::m_screenChanged = false;

MainWindow::MainWindow()
{
}

MainWindow::~MainWindow()
{
	if (m_currentScreen != NULL)
		delete m_currentScreen;
	TTF_CloseFont(MainWindow::m_font);
	TTF_Quit();
	SDL_Quit();
}

bool MainWindow::init()
{
	if (this->init_sdl() == false)
		return (false);
	SDL_Surface* icon = IMG_Load("images\\logo.png");
	SDL_WM_SetCaption("Gomoku", NULL);
	SDL_WM_SetIcon(icon, NULL);
	if (this->init_ttf() == false)
		return (false);
	m_font = TTF_OpenFont("fonts/Karate.ttf", 18);
	if (m_font == NULL)
		COUT_ENDL(std::string("Error font: ") + TTF_GetError());
	PlayerTurnPrompter::Instance().init();
	MainWindow::SelectScreen(new class SelectScreen);
	return (true);
}

bool MainWindow::init_sdl()
{
	if (SDL_Init(SDL_INIT_VIDEO) == -1)
		return (false);
	
	SDL_putenv("SDL_VIDEO_CENTERED=1");
	m_screen = SDL_SetVideoMode(800, 672, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
	if (m_screen == NULL)
		return (false);
	return (true);
}

bool MainWindow::init_ttf()
{
	if (TTF_Init() == -1)
		return (false);
	return (true);
}

bool MainWindow::update()
{
	SDL_PollEvent(&MainWindow::m_event);
	
	if (m_currentScreen != NULL)
	{
		m_currentScreen->doEvents();
		if (m_currentScreen->draw() == false)
			return (false);
	}

	if (SDL_Flip(MainWindow::m_screen) == -1)
		return (false);
	return (true);
}

SDL_Surface* MainWindow::Screen()
{
	return (MainWindow::m_screen);
}

SDL_Event& MainWindow::Event()
{
	return (MainWindow::m_event);
}

void MainWindow::Close(bool _value)
{
	MainWindow::m_close = _value;
}

bool MainWindow::IsClosed()
{
	return (MainWindow::m_close);
}

TTF_Font* MainWindow::Font()
{
	return (MainWindow::m_font);
}

void MainWindow::SelectScreen(IScreen* _screen)
{
	if (_screen != NULL)
	{
		delete MainWindow::m_currentScreen;
		MainWindow::m_currentScreen = _screen;
		MainWindow::m_currentScreen->init();
		MainWindow::m_screenChanged = true;
	}
}

bool MainWindow::ScreenHasChanged()
{
	return (MainWindow::m_screenChanged);
}

void MainWindow::ResetScreenChanged()
{
	MainWindow::m_screenChanged = false;
}